package cn.itsource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
import cn.itsource.bean.*;
import cn.itsource.config.PageList;
import cn.itsource.dto.ProductDto;
import cn.itsource.expection.BusinessException;
import cn.itsource.mapper.OrderAddressMapper;
import cn.itsource.mapper.ProductMapper;
import cn.itsource.pay.dto.PayDto;
import cn.itsource.pay.service.AlipayInfoServiceImpl;
import cn.itsource.query.ProductQuery;
import cn.itsource.service.*;
import cn.itsource.util.JsonResult;
import cn.itsource.util.MyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.itsource.util.PetHomeConstant.PRODUCT.*;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-29 09:43:00
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Resource
    private IProductDetailService productDetailService;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private IUserAddressService userAddressService;

    @Resource
    private OrderAddressMapper orderAddressMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IOrderAdoptService orderAdoptService;

    @Resource
    private AlipayInfoServiceImpl alipayInfoService;

    @Resource
    private IProductCommentService productCommentService;


    @Override
    public JsonResult getPage(ProductQuery query) {
        Page<Product> page = new Page<>(query.getPage(),query.getRows());

        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Strings.isNotEmpty(query.getStartTime()),Product::getCreatetime,query.getStartTime()).
                le(Strings.isNotEmpty(query.getEndTime()),Product::getCreatetime,query.getEndTime());
        queryWrapper.like(Strings.isNotEmpty(query.getKeyword()),Product::getName,query.getKeyword());


        Page<Product> messagePage = this.page(page, queryWrapper);
        List<Product> records = messagePage.getRecords();



        PageList<Product> pageList = new PageList<>();

        pageList.setTotal(messagePage.getTotal());
        pageList.setList(records);
        return JsonResult.success(pageList);
    }

    @Override
    public JsonResult upState(ProductQuery query, Long state) {
        List<Long> ids = query.getIds();

        //更改状态
        if (state==PRODUCT_STATE_DOWN){
            List<Product> pets = this.listByIds(ids);
            pets = pets.stream().map(item->{
                item.setState(PRODUCT_STATE_DOWN);
                item.setOffsaletime(LocalDateTime.now());
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(pets);
        }else if (state == PRODUCT_STATE_UP){
            List<Product> pets = this.listByIds(ids);
            pets = pets.stream().map(item->{
                item.setState(PRODUCT_STATE_UP);
                item.setOnsaletime(LocalDateTime.now());
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(pets);
        }else if (state == PRODUCT_STATE_BY){
            List<Product> pets = this.listByIds(ids);
            pets = pets.stream().map(item->{
                item.setState(PRODUCT_STATE_UP);
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(pets);
        }

        return JsonResult.success("更改成功");
    }

    @Override
    public JsonResult getPetById(Long id) {
        //通过id获取具体数据
        Product product = this.getById(id);

        LambdaQueryWrapper<ProductDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductDetail::getProductId,id);
        ProductDetail detail = productDetailService.getOne(queryWrapper);


        LambdaQueryWrapper<ProductComment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(ProductComment::getProductId,id);
        List<ProductComment> list = productCommentService.list(commentLambdaQueryWrapper);



        //通过查询填充数据
        if (CollectionUtil.isEmpty(list)){
            ArrayList<ProductComment> productComments = new ArrayList<>();
            product.setCommentList(productComments);
        }else {
            product.setCommentList(list);
        }


        if (detail!=null) {
            product.setDetail(detail);
        }else {
            ProductDetail productDetail = new ProductDetail();
            product.setDetail(productDetail);
        }

        return JsonResult.success(product);
    }

    @Override
    public JsonResult add(Product product) {
        if (product.getId()==null){
            //获取到数据后，将状态默认为下架
            product.setState(PRODUCT_STATE_DOWN);

            //设置创建时间
            product.setCreatetime(LocalDateTime.now());

            //先保存pet,获取到id
            productMapper.insert(product);

            ProductDetail detail = product.getDetail();
            detail.setProductId(product.getId());

            //存入商品详细信息表
            productDetailService.save(detail);
        }else {
            this.updateById(product);
            ProductDetail detail = product.getDetail();
            //存入商品详细信息表
            productDetailService.updateById(detail);
        }


        return JsonResult.success("保存成功");
    }

    @Override
    @Transactional
    public JsonResult deleteByIds(ProductQuery query) {

        //获取到的ids遍历删除，并且删除相关的详情
        List<Long> ids = query.getIds();
        this.removeByIds(ids);
        for (Long id :
        ids) {
            //删除详情
            LambdaQueryWrapper<ProductDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductDetail::getProductId,id);
            productDetailService.remove(queryWrapper);
        }
        return JsonResult.success("删除成功");
    }

    @Override
    @Transactional
    public String submitOrder(ProductDto productDto) {
        Long addressId = productDto.getAddressId();//地址id
        Long productId = productDto.getProductId();//服务id


        //根据用户地址id查询到用户的地址对象
        UserAddress userAddress = userAddressService.getById(addressId);
        //判空
        if (userAddress==null){
            throw new BusinessException("地址不存在");
        }

        //把对象地址拷贝到订单地址信息
        OrderAddress orderAddress = BeanUtil.copyProperties(userAddress, OrderAddress.class);
        orderAddress.setId(null);

        //保存用户地址信息，获取id
        orderAddressMapper.insert(orderAddress);

        Long id = orderAddress.getId();

        //获取服务信息
        Product product = this.getById(productId);
        //判空
        if (product==null) {
            throw new BusinessException("商品信息异常");
        }

        //讲订单地址的主键id设置给订单对象
        OrderAdopt orderAdopt = new OrderAdopt();
        orderAdopt.setDigest("用户地址id:"+addressId+",商品id="+productId);
        //设置支付状态
        orderAdopt.setState(0);
        String costprice = product.getCostprice();
        Long aLong = Long.valueOf(costprice);
        //设置订单待支付金额
        orderAdopt.setPrice(BigDecimal.valueOf(aLong));


        //雪花算法设置订单编号
        String orderSn = new Snowflake().nextIdStr();
        orderAdopt.setOrderSn(orderSn);
        orderAdopt.setLastConfirmTime(LocalDateTime.now());
        orderAdopt.setPetId(productId);

        //获取用户id
        Long uid = MyUtils.getUid(stringRedisTemplate);
        orderAdopt.setUserId(uid);
        //设置店铺id


        //地址id
        orderAdopt.setAddressId(id);


        //入库订单数据
        orderAdoptService.save(orderAdopt);


        PayDto payDto = new PayDto();
        payDto.setMoney(Double.valueOf(product.getCostprice()));
        payDto.setSubject(product.getName());
        payDto.setSubjectDesc("宠物订单："+orderSn);
        payDto.setOrderSn(orderSn);


        //销量可以+1
        if (product.getSalecount()!=null){
            product.setSalecount(product.getSalecount()+1l);
        }else {
            product.setSalecount(1l);
        }
        this.updateById(product);

        //跳转到支付
        return alipayInfoService.goBuy(payDto);
    }
}
